<template>
  <view class="login-layout">
    <u-navbar title="登录" bgColor="transparent" :autoBack="false" :placeholder="true" @leftClick="back"></u-navbar>
    <view class='login-content'>
        <view class="logo-box">
          <u--image
              width="288rpx"
              height="288rpx"
              :src="'/static/user/login-logo.png'"
            ></u--image>
            <u--image
              width="248rpx"
              height="44rpx"
              :src="'/static/user/appname.png'"
            ></u--image>
        </view>
        <view class="button" v-if="loginType =='weixin'">
          <button class="btn btn-yellow" open-type="getPhoneNumber" @getphonenumber="phoneLogin">一键授权登录</button>
          <!-- <view class="btn" @click.stop="loginType = 'phone'">其他手机号登录</view> -->
        </view>
        <!-- <view class="login_from" v-if="loginType !='weixin'">
          <view class="login_from_li">
            <text class="tip flex_shrink">+86</text>
            <input class="login_from_input" placeholder="输入手机号码" v-model="mobile" />
          </view>
          <view class="login_from_li">
            <input type="number" class="login_from_input" placeholder="输入验证码" v-model="phoneCode" />
            <text class="code flex_shrink" @click="getCode">{{phoneCodeMessage}}</text>
          </view>
          <view class="btn btn-yellow">登录</view>
        </view> -->
        <view class="privacy" @click="checkboxValue = !checkboxValue">
            <view class="checkbox-box" :class="checkboxValue ? 'active' : ''"></view>
            <view>我已阅读并同意<span class="color_link" @click.stop="
                  routerJump('http://ta.jiyaqi.com/policy/app_privacy.html','隐私政策')
                ">《隐私政策》</span>
              、
              <span class="color_link" @click.stop="
                  routerJump('http://ta.jiyaqi.com/policy/app_user_policy.html','用户协议')
                ">《用户协议》</span>
            </view>
        </view>
    </view>

  </view>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex'
import { wxappAuth, getUser, getUserInfo } from '@/api/user'
import { login, authorize, getProvider } from '@/utils'
import dayjs from 'dayjs'
import cookie from '@/utils/store/cookie'
import store from '@/store'
export default {
  data() {
    return {
      authorize: false,
      canIUseGetUserProfile: false,
      LoginCode: '',
      loginType:"weixin",
      checkboxValue: false,
      mobile: '',
      password: '',
      logining: false,
      phoneCode: '',
      phoneCodeMessage:"获取验证码",
      count: 0,
      timer: null,
    }
  },
  computed: {
    ...mapState(['isAuthorization', '$deviceType', 'token']),
  },
  onLoad() {
    this.UNILogin()
    if (wx.getUserProfile) {
      this.canIUseGetUserProfile = true
    }
    // // 先校验用户是否授权，如果没有授权，显示授权按钮
  },
  methods: {
    ...mapActions(['changeAuthorization', 'setUserInfo']),
    ...mapActions('user', ['GetUserInfo',]),
    ...mapMutations(['updateAuthorizationPage']),
    ...mapMutations('user', [
      'SET_U_ADDRESS',
      'SET_TOKEN',
      'SET_NOREADNUM',
      'SET_SHOWLOCATION',
    ]),
    getUserInfoBtn(data) {
      console.log(data)
      console.log('getUserInfoBtn')
      if (data.detail.errMsg == 'getUserInfo:fail auth deny') {
        uni.showToast({
          title: '取消授权',
          icon: 'none',
          duration: 2000,
        })
        return
      }
      uni.showLoading({
        title: '登录中',
      })
      login()
        .then(e => {
          uni.hideLoading()
          console.log('重定向')
          this.$yrouter.reLaunch({
            path: cookie.get('redirect').replace(/\ /g, ''),
          })
        })
        .catch(error => {
          uni.hideLoading()
          console.log(error)
          uni.showToast({
            title: error,
            icon: 'none',
            duration: 2000,
          })
        })
    },
    // 申请获取用户信息
    getUserInfoProfile(data) {
      console.log('getUserInfoProfile')
      wx.getUserProfile({
        lang: 'zh_CN',
        desc: '需要获取您的信息用来展示',
        success: res => {
          console.log('用户信息', res)
          uni.showLoading({
            title: '登录中',
          })
          login(res)
            .then(e => {
              console.log('重定向')
              this.$yrouter.reLaunch({
                path: cookie.get('redirect').replace(/\ /g, ''),
              })
            })
            .catch(error => {
              console.log(error)
              uni.showToast({
                title: error,
                icon: 'none',
                duration: 2000,
              })
            })
        },
      })
    },
    UNILogin() {
      getProvider()
        .then(provider => {
          console.log('当前的环境商', provider)
          if (!provider) {
            reject()
          }
          // uni登录
          uni.login({
            provider: provider,
            success: async loginRes => {
              console.log('uni.login登录成功', loginRes, cookie.get('spread'))
              this.LoginCode = loginRes.code // 获取开发code
              cookie.set('wxLoginCode', loginRes.code)
            },
          })
        })
        .catch(err => { })
    },
	  // 微信用户手机号登录
	  phoneLogin(e) {
	    console.log('用户微信手机号登录', e)
      if (!this.checkboxValue) return uni.$u.toast('请阅读并勾选以下政策与协议')
	    if (e.mp.detail.errMsg == 'getPhoneNumber:ok') {
	      console.log(e.mp.detail)
	      uni.showLoading({
	        title: '登录中',
	      })
	      wxappAuth({
	        encryptedData: e.mp.detail.encryptedData,
	        iv: e.mp.detail.iv,
	        // code: this.LoginCode,
	        code: this.LoginCode,
	        spread: cookie.get('spread'),
	      })
	        .then(async res => {
	          console.log('登录成功,开始处理登录信息保存，并获取用户详情')
	          //app--- 存储的token及获取用户信息
	          uni.setStorageSync('Token', res.data.token)
	          this.SET_TOKEN(res.data.token)
	          // this.getLocation()
	          await this.GetUserInfo()
	          store.commit('login', res.data.token, dayjs(res.data.expires_time))
	          store.dispatch('userInfo', true)
	          getUserInfo()
	            .then(user => {
	              console.log('获取用户信息成功1')
                console.log(user)
	              uni.setStorageSync('uid', user.data.uid)
	              store.dispatch('setUserInfo', user.data)
	              uni.hideLoading()
	              uni.navigateBack()
	            })
	            .catch(error => {
	              console.log('获取用户信息失败')
	              uni.hideLoading()
	            })
	        })
	        .catch(error => {
	          console.log(error)
	          console.log('登录接口调用失败')
	          this.UNILogin()
	          uni.hideLoading()
	        })
	    } else {
	      uni.hideLoading()
	      uni.showToast({
	        title: '已拒绝授权',
	        icon: 'none',
	        duration: 2000,
	      })
	    }
	  },
    //获得验证码
    async getCode () {
      console.log("发送验证码")
      if(this.count > 0) return
      let reg = /^[1]\d{10}$/
      if (this.mobile == '') return uni.$u.toast('请输入手机号')
      if (!reg.test(this.mobile)) return uni.$u.toast('手机号格式有误')
      if (!this.checkboxValue) return uni.$u.toast('请阅读并勾选以下政策与协议')

      //await GetCode({ phone: this.mobile })
      uni.showToast({
        title: '验证码已发送',
        icon: 'success',
        mask: false,
        duration: 2000,
      })
      this.timeRun()
    },
    timeRun () {
      const TIME_COUNT = 60
      if (!this.timer) {
        this.count = TIME_COUNT

        this.timer = setInterval(() => {
          this.phoneCodeMessage = this.count + 's后重新获取'
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--
          } else {
            clearInterval(this.timer)
            this.timer = null
            this.phoneCodeMessage = '获取验证码'
          }
        }, 1000)
      }
    },
    routerJump (url, type) {
      if(type != 'phone'){
        console.log(111)
          this.toPage(`public/webview?url=${url}&type=${type}`, false)
      }else{
        console.log(222)
          uni.navigateTo({
              url: "/packageAuth/pages/authorization/phoneLogin",
          })
      }
    },
    back() {
      console.log(this.loginType)
      if(this.loginType == 'weixin'){
        console.log(1111)
         let jump = uni.getStorageSync('isJump')
      if (jump) uni.removeStorageSync('isJump')
      uni.navigateBack()
      }else{
        console.log(2222)
        this.loginType = 'weixin'
      }

    }
  },
  mounted() {
    if (wx.getUserProfile) {
      this.canIUseGetUserProfile = true
      console.log(this.canIUseGetUserProfile)
    }
  },
}
</script>

<style lang="scss">
.login-layout{
  height:100%;
  background: #fff;
  .login-content{
    height:calc( 100% - 130rpx);

    box-sizing: border-box;
    .logo-box{
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 80rpx 20rpx;
    }
    .button{
      display: flex;
      flex-direction: column;
      gap: 40rpx;
      padding: 0 80rpx;
    }
    .btn{
        width: 100%;
        height: 88rpx;
        border-radius: 9999rpx;
        border: 1rpx solid #DBDDE0;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 32rpx;
        color: #1F2329;
        line-height: 88rpx;
        text-align: center;
      }
      .btn-yellow{
        background: #FF5900;
        border-color: #FF5900;
        color: #fff;
      }
    .login_from{
      display: flex;
      flex-direction: column;
      gap: 40rpx;
      padding: 0 80rpx;
      .login_from_li{
        display: flex;
        align-items: center;
        height: 88rpx;
        border-radius: 9999rpx;
        padding: 0 30rpx;
        font-size: 28rpx;
        border: 1rpx solid #DBDDE0;
        font-family: PingFangSC, PingFang SC;
        .login_from_input{
          flex: 1;
        }
        .tip{
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          color: #1F2329;
          padding-right: 30rpx;
        }
        .code{
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 28rpx;
          color: #FF5900;
          line-height: 28rpx;
        }
      }
    }
    .privacy{
      position: absolute;
      left: 0;
      right: 0;
      bottom: 100rpx;
      display: flex;
      align-items: center;
      gap: 5px;
      padding: 0 20rpx 0px 80rpx;
      font-size: 26rpx;
    }
    .checkbox-box{
       width: 32rpx;
       height: 32rpx;
       border:1px solid #c8c9cc;
       border-radius: 50%;
       &.active{
        position: relative;
        border-color: #FF5900;
        background: #FF5900;
        &::after{
          position: absolute;
          content:"✔";
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          color: #fff;
        }
       }
    }
    .color_link{
      color: #FF5900;
    }
  }
}
</style>
